package com.hmall.item.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private ItemMapper mapper;

    @Override
    public PageDTO page(Integer page, Integer size) {
        Page<Item> itemPage = new Page<>(page,size);
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Item::getCreateTime);
        Page<Item> selectPage1 = mapper.selectPage(itemPage, queryWrapper);
        List<Item> records = selectPage1.getRecords();
        long total = selectPage1.getTotal();
        PageDTO<Item> itemPageDTO = new PageDTO<>();
        itemPageDTO.setTotal(total);
        itemPageDTO.setList(records);
        return itemPageDTO;
    }


    @Override
    public boolean update(Long itemId,int num) {
        Item item = mapper.selectById(itemId);
        Integer sold = item.getSold();
        if(sold==null){
          throw new RuntimeException();
        }
        Integer sold0=sold-num;
        item.setSold(sold0);
        return true;
    }




    @Override
   public void recoverStock(Long itemId, Integer num) {
        Item item = this.getById(itemId);
        item.setStock(item.getStock() + num);
        this.updateById(item);
    }
}
